package com.glasses.orm.utils.ExcelUtils;

import com.glasses.orm.utils.BeanToMapUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

;


/**
 * 导出Excel
 * Created by ashin on 2018/7/4.
 */
public class ExportExcelUtil<T> {

    protected final Logger logger = LoggerFactory.getLogger(ExportExcelUtil.class);

    //总数超过默认3W条 换下一个工作sheet
    private int pageRowNo = 30000;

    public int getPageRowNo() {
        return pageRowNo;
    }

    public void setPageRowNo(int pageRowNo) {
        this.pageRowNo = pageRowNo;
    }

    /**
     * 获得输出流
     *
     * @param filename
     * @param response
     * @return
     * @throws IOException
     */
    public OutputStream getOutpuStream(String filename, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "ISO8859-1"));
        return response.getOutputStream();
    }

    /**
     * 导出 xls格式Excel HSSF
     *
     * @param title
     * @param headers
     * @param columns
     * @param dataset
     * @param out
     * @param pattern
     */
    public void exportHSExcelByColumn(String title, String[] headers, String[] columns, Collection<T> dataset,
                                      OutputStream out, String pattern) {

        Workbook workbook = new SXSSFWorkbook();
        // 生成一个表格
        Sheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth(20);
        sheet.setDefaultRowHeightInPoints(24);
        // 生成一个 表格标题行样式
        CellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        // 生成一个字体
        Font font = workbook.createFont();
        font.setColor(IndexedColors.WHITE.getIndex());
        font.setFontHeightInPoints((short) 12);
        font.setBold(true);
        // font.setBoldweight((short)700));
        // 把字体应用到当前的样式
        style.setFont(font);

        // 生成并设置另一个样式 内容的背景
        CellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style2.setBorderBottom(BorderStyle.THIN);
        style2.setBorderLeft(BorderStyle.THIN);
        style2.setBorderRight(BorderStyle.THIN);
        style2.setBorderTop(BorderStyle.THIN);
        style2.setAlignment(HorizontalAlignment.CENTER);
        style2.setVerticalAlignment(VerticalAlignment.CENTER);
        // 生成另一个字体
        Font font2 = workbook.createFont();
        font.setBold(true);
        // font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);

        // 声明一个画图的顶级管理器
        Drawing<?> patriarch = sheet.createDrawingPatriarch();
        // 定义注释的大小和位置
        Comment comment = patriarch.createCellComment(new HSSFClientAnchor(0, 0, 0,
                0, (short) 4, 2, (short) 6, 5));
        // 设置注释内容
        comment.setString(new HSSFRichTextString("Created By Ashin"));
        // 设置注释作者，当鼠标移动到单元格上是可以在状态栏中看到该内容.
        comment.setAuthor("Ashin");

        // 产生表格标题行
        Row row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(style);
            RichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        if (StringUtils.isEmpty(pattern)) {
            pattern = "yyyy/MM/dd";
        }
        FastDateFormat instance = FastDateFormat.getInstance(pattern);
        // 遍历集合数据，产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        int count = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = (T) it.next();
            // 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值

            // Field[] fields = t.getClass().getDeclaredFields();
            count = headers.length < columns.length ? headers.length : columns.length;
            for (int i = 0; i < count; i++) {
                Cell cell = row.createCell(i);
                cell.setCellStyle(style2);
                String fieldName = columns[i];
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                try {
                    Class<? extends Object> tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
                    Object value = getMethod.invoke(t, new Object[]{});
                    // 判断值的类型后进行强制类型转换
                    String textValue = null;
                    if (value instanceof Date) {
                        Date date = (Date) value;
                        textValue = instance.format(date);
                    } else if (value instanceof byte[]) {
                        // 有图片时，设置行高为60px;
                        row.setHeightInPoints(60);
                        // 设置图片所在列宽度为80px,注意这里单位的一个换算
                        sheet.setColumnWidth(i, (short) (35.7 * 80));
                        // sheet.autoSizeColumn(i);
                        byte[] bsValue = (byte[]) value;
                        ClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index);
                        anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE);
                        patriarch.createPicture(anchor, workbook.addPicture(bsValue, SXSSFWorkbook.PICTURE_TYPE_JPEG));
                    } else {
                        // 其它数据类型都当作字符串简单处理
//						if (value != null) {
//							textValue = value.toString();
//							if (textValue.equalsIgnoreCase("VLD")) {
//								textValue = "有效";
//							} else if (textValue.equalsIgnoreCase("IVD")) {
//								textValue = "无效";
//							}
//						} else {
//							textValue = "";
//						}
                    }
                    // 如果不是图片数据，就利用正则表达式判断textValue是否全部由数字组成
                    if (textValue != null) {
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            RichTextString richString = new HSSFRichTextString(textValue);
                            Font font3 = workbook.createFont();
                            font3.setColor(IndexedColors.BLACK.index); // 内容
                            richString.applyFont(font3);
                            cell.setCellValue(richString);
                        }
                    }
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(workbook);
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * 导出 xlsx格式Excel XSSF
     *
     * @param title
     * @param dataset
     * @param out
     * @param pattern
     */
    public void exportXSExcelByColumn(String title, List<T> dataset, OutputStream out, String pattern, ExcelUtilBean excelUtilBean) {

        //开始导出计时
        long enterTime = new Date().getTime();

        //判断dataset是否为空
        if (dataset.size() == 0) {
            logger.debug("---- 数据集为空，请查询后重新导出 ----");
            return;
        }

        logger.debug("---- 开始导出 《{}》 ----", title);
        SXSSFWorkbook workbook = new SXSSFWorkbook(100);
        workbook.setCompressTempFiles(true);
        // 生成一个 表格标题行样式
        CellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        // 生成一个字体
        Font font = workbook.createFont();
        font.setColor(IndexedColors.WHITE.getIndex());
        font.setFontHeightInPoints((short) 12);
        font.setBold(true);
        // font.setBoldweight((short)700));
        // 把字体应用到当前的样式
        style.setFont(font);

        // 生成并设置另一个样式 内容的背景
        CellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style2.setBorderBottom(BorderStyle.THIN);
        style2.setBorderLeft(BorderStyle.THIN);
        style2.setBorderRight(BorderStyle.THIN);
        style2.setBorderTop(BorderStyle.THIN);
        style2.setAlignment(HorizontalAlignment.CENTER);
        style2.setVerticalAlignment(VerticalAlignment.CENTER);
        // 生成另一个字体
        Font font2 = workbook.createFont();
        font.setBold(true);
        // font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);
//
//        // 声明一个画图的顶级管理器
//        Drawing<?> patriarch = sheet.createDrawingPatriarch();
//        // 定义注释的大小和位置
//        Comment comment = patriarch.createCellComment(new XSSFClientAnchor(0, 0, 0,
//                0, (short) 4, 2, (short) 6, 5));
//        //设置注释内容
//        comment.setString(new XSSFRichTextString("Created By Ashin"));
//        // 设置注释作者，当鼠标移动到单元格上是可以在状态栏中看到该内容.
//        comment.setAuthor("Ashin");

        String[] headers = null;
        String[] columns = null;
        if (excelUtilBean == null) {
            List<String> headersList = new ArrayList<>();

            List<String> columnsList = new ArrayList<>();
            Object object = dataset.get(0);
            Class clazz = object.getClass();// 获取集合中的对象类型
            Field[] fields = clazz.getDeclaredFields();// 获取他的字段数组
            for (Field field : fields) {
                ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                if (annotation != null) {
                    headersList.add(annotation.value());
                    columnsList.add(field.getName());
                }
            }

            logger.debug("参数header为: {}", headersList);
            logger.debug("参数columns为: {}", columnsList);

            //標題
            headers = headersList.toArray(new String[headersList.size()]);
            //列名
            columns = columnsList.toArray(new String[columnsList.size()]);
        } else {
            headers = excelUtilBean.getHeaders();
            columns = excelUtilBean.getColumns();
        }

        if (StringUtils.isEmpty(pattern)) {
            pattern = "yyyy/MM/dd";
        }
        FastDateFormat instance = FastDateFormat.getInstance(pattern);
        // 遍历集合数据，产生数据行
        Iterator<T> it = dataset.iterator(); // 多个T集合
        int rowNo = 0;
        int count = 0;
        //定义页数
        int _pageRowNo = 0;

        Sheet sheet = null;
        Row row = null;

        while (it.hasNext()) {

            //判断当前行数有没有超过换页行数
            if (_pageRowNo % pageRowNo == 0) {
                logger.debug("正在导出第 {} 个工作簿的数据", rowNo / pageRowNo);
                sheet = workbook.createSheet(title + "_" + (rowNo / pageRowNo));//建立新的sheet对象
                //sheet = workbook.getSheetAt(rowNo / pageRowNo);        //动态指定当前的工作表
                setSheetStyle(sheet);
                row = sheet.createRow(0);
                for (int i = 0; i < headers.length; i++) {
                    Cell cell = row.createCell(i);
                    cell.setCellStyle(style);
                    RichTextString text = new XSSFRichTextString(headers[i]);
                    cell.setCellValue(text);
                }
                _pageRowNo = 0;
            }
            _pageRowNo++;
            rowNo++;
            row = sheet.createRow(_pageRowNo);
            T t = it.next();
            Map map = null;
            if (t instanceof Map)
                map = (Map) t;
            else {
                try {
                    map = BeanToMapUtil.convertBean(t);
                } catch (IntrospectionException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            count = headers.length < columns.length ? headers.length : columns.length;
            StringBuilder sbr = new StringBuilder();
            for (int i = 0; i < count; i++) {
                Cell cell = row.createCell(i);
                cell.setCellStyle(style2);
                try {
                    Object value = map.get(columns[i]);
                    // 判断值的类型后进行强制类型转换
                    String textValue = null;
                    if (value instanceof Date) {
                        Date date = (Date) value;
                        textValue = instance.format(date);
                    } else if (value instanceof byte[]) {
                        // 有图片时，设置行高为60px;
                        row.setHeightInPoints(60);
                        // 设置图片所在列宽度为80px,注意这里单位的一个换算
                        sheet.setColumnWidth(i, (short) (35.7 * 80));
                        // sheet.autoSizeColumn(i);
                        byte[] bsValue = (byte[]) value;
//                        ClientAnchor anchor = new XSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index);
//                        anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE);
//                        patriarch.createPicture(anchor, workbook.addPicture(bsValue, Workbook.PICTURE_TYPE_JPEG));
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        if (value != null) {
                            textValue = value.toString();
                            // if (textValue.equalsIgnoreCase("VLD")) {
                            // textValue = "有效";
                            // } else if (textValue.equalsIgnoreCase("IVD")) {
                            // textValue = "无效";
                            // }
                        } else {
                            textValue = "";
                        }
                    }
                    sbr.append(textValue).append(",");

                    // 如果不是图片数据，就利用正则表达式判断textValue是否全部由数字组成
                    if (textValue != null) {
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            RichTextString richString = new XSSFRichTextString(textValue);
                            Font font3 = workbook.createFont();
                            font3.setColor(IndexedColors.BLACK.index); // 内容
                            richString.applyFont(font3);
                            cell.setCellValue(richString);
                        }
                    }
                } catch (SecurityException e) {
                    e.printStackTrace();
                }
            }
//            logger.debug("第{}条数据：{} ", rowNo, sbr.substring(0, sbr.length() - 1));
        }
        try {
            workbook.write(out);
            logger.debug("---- 导出结束，总行数为：{} 条，总耗时：{} ms ----", rowNo, new Date().getTime() - enterTime);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(workbook);
            IOUtils.closeQuietly(out);
        }
    }

    //定义表格样式
    private void setSheetStyle(Sheet sheet) {
        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth(20);
        sheet.setDefaultRowHeightInPoints(24);
    }

}
